﻿using System.Reflection;

public class MethodInjector
{
    public string A;
    public string[] args;

    public System.Object m___this;

    public object InjectionMethod()
    {
        string msg = string.Format("Hello World from inside {0}!", this);
        System.Console.WriteLine(msg);

        /* You can see the result of this intruding method if you turn on the visual studio output window. (menue: View -> Output) */
        return null;
    }
}

public static class ReflectionExtensions
{
    public static T GetPropertyContent<T>(this object source, string propName)
    {
        PropertyInfo pi = GetProperty(source, propName);
        return (T)pi.GetValue(source, null);
    }

    public static void SetPropertyContent(this object source, object value, string propName)
    {
        PropertyInfo pi = GetProperty(source, propName);
        pi.SetValue(source, value, null);
    }

    private static PropertyInfo GetProperty(object source, string propName)
    {
        var bindingFlagVariants =
            new[] {
                                    (BindingFlags.Instance),
                                    (BindingFlags.Instance | BindingFlags.NonPublic),
                                    (BindingFlags.Static),
                                    (BindingFlags.Static | BindingFlags.NonPublic)
                                };
        PropertyInfo pi = source.GetType().GetProperty(propName);
        if (pi != null)
            return pi;
        foreach (var flags in bindingFlagVariants)
        {
            pi = source.GetType().GetProperty(propName, flags);
            if (pi != null)
                break;
        }
        return pi;
    }
}